//
//  HWHomeViewController.m
//  黑马微博2期
//
//  Created by apple on 14-10-7.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HWHomeViewController.h"
#import "HWitermTool.h"
#import "UIBarButtonItem+Extension.h"
#import "HWTitleButton.h"
#import "HWDropdownMenu.h"
#import "HWDropViewController.h"
#import "HWAccountTool.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "HWStatus.h"
#import "MJRefresh.h"
#import "HWStatusCell.h"
#import "HWstatusFrame.h"
@interface HWHomeViewController ()<HWDropdownMenuDelegate>
@property (nonatomic, strong) NSMutableArray *statusFrames;
@end
@implementation HWHomeViewController
#pragma mark - 数组懒加载
- (NSMutableArray *)statusFrames
{
    if (!_statusFrames) {
        self.statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    /**设置tableView颜色*/
    self.tableView.backgroundColor = HWColor(211, 211, 211);
    
//    self.tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0);
    /**设置导航栏上面的内容*/
    [self setupNav];
    /*设置用户信息**/
    [self setupUserInfo];
    /*请求微博数据**/
//    [self requestStatus];
    /* 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）**/
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    [self.tableView.header beginRefreshing];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 禁止自动加载
    footer.automaticallyRefresh = NO;
    
    // 设置footer
    self.tableView.footer = footer;
    
    // 获得未读数
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
    // 主线程也会抽时间处理一下timer（不管主线程是否正在其他事件）
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    
}

/**
 *  获得未读数
 */
- (void)setupUnreadCount
{
    //    HWLog(@"setupUnreadCount");
    //    return;
    // 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.拼接请求参数
    HWAccount *account = [HWAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = account.uid;
    
    // 3.发送请求
    [mgr GET:@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        // 微博的未读数
        //        int status = [responseObject[@"status"] intValue];
        // 设置提醒数字
        //        self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", status];
        
        // @20 --> @"20"
        // NSNumber --> NSString
        // 设置提醒数字(微博的未读数)
        NSString *status = [responseObject[@"status"] description];
        if ([status isEqualToString:@"0"]) { // 如果是0，得清空数字
            self.tabBarItem.badgeValue = nil;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        } else { // 非0情况
            self.tabBarItem.badgeValue = status;
            [UIApplication sharedApplication].applicationIconBadgeNumber = status.intValue;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        HWLog(@"请求失败-%@", error);
    }];
}
- (void)loadMoreData{
    HWAccount *account = [HWAccountTool account];
    //   1. 请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //  2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    HWStatusFrame *statusF = [self.statusFrames lastObject];
    if (statusF) {
        params[@"max_id"] = statusF.status.idstr;
    }
    //  3.发送请求
    [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        NSArray *array = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        //转为statusFrame模型数组
        NSArray *newStatusFrame = [self statusFrameWithStatus:array];
        // 刷新表格
        NSIndexSet *set = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(self.statusFrames.count -1, array.count)];
        [self.statusFrames removeObjectAtIndex:self.statusFrames.count -1];
        [self.statusFrames insertObjects:newStatusFrame atIndexes:set];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.tableView.footer endRefreshing];
    }];
}

/**
 *  加载最新数据
 */
- (void)loadNewData{ 
    HWAccount *account = [HWAccountTool account];
    //   1. 请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //  2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    HWStatusFrame *statusF =  [self.statusFrames firstObject];
    if (statusF) {
        params[@"since_id"] = statusF.status.idstr;
    }
    
    //  3.发送请求
    [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        NSArray *array = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        //转为statusFrame模型数组
        NSArray *newStatusFrame = [self statusFrameWithStatus:array];
        // 刷新表格
        NSIndexSet *set = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, newStatusFrame.count)];
        [self.statusFrames insertObjects:newStatusFrame atIndexes:set];
        [self.tableView reloadData];
        //设置显示新微薄条数
        [self setupStatusCount:array.count];
        [self.tableView.header endRefreshing];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.tableView.header endRefreshing];
    }];
}

/**
 *  将status数组转换为statusFrame数组
 *
 *  @param status模型数组
 *
 *  @return statusArray frame数组
 */
- (NSArray *)statusFrameWithStatus:(NSArray *)statusArray{
    NSMutableArray *newStatusFrame = [NSMutableArray array];
    for (HWStatus *status in statusArray) {
        HWStatusFrame *statusFrame = [[HWStatusFrame alloc] init];
        statusFrame.status = status;
        [newStatusFrame addObject:statusFrame];
    }
    return newStatusFrame;
}
/**
 *设置显示新微薄条数
 */
- (void)setupStatusCount:(NSInteger)count{
    self.tabBarItem.badgeValue = nil;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.width = [UIScreen mainScreen].bounds.size.width;
    label.height = 30;
    label.x = 0;
    label.y = 64 - label.height;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    if (count == 0) {
        label.text = @"没有新数据";
    }else{
        label.text = [NSString stringWithFormat:@"共刷新了%ld条数据",count];
    }
//    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    CGFloat duration = 1.0;
    [UIView animateWithDuration:duration animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:duration delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

/**
 *
 * 设置用户信息
 */
- (void)setupUserInfo{
    HWAccount *account = [HWAccountTool account];
    //   1. 请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //  2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = account.uid;
    //  3.发送请求
    [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
    HWTitleButton *titleBtn = (HWTitleButton*)self.navigationItem.titleView;
    [titleBtn setTitle:responseObject[@"name"] forState:UIControlStateNormal];
    account.name = responseObject[@"name"];
    [HWAccountTool saveAccountWithAccount:account];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@",error);
}];
}
/**
 *  设置导航栏上面的内容
 */
- (void)setupNav{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itermWithTarget:self Action:@selector(friendsearch) Image:@"navigationbar_friendsearch" highlightedImage:@"navigationbar_friendsearch_highlighted"];
    //设置图片
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itermWithTarget:self Action:@selector(pop) Image:@"navigationbar_pop" highlightedImage:@"navigationbar_pop_highlighted"];
    HWTitleButton *titleButton = [[HWTitleButton alloc] init];
//    [titleButton sizeToFit];
    NSString *name = [HWAccountTool account].name;
    [titleButton setTitle:name?name:@"首页" forState:UIControlStateNormal];
    [titleButton addTarget:self action:@selector(titleClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
}

/**
 *  标题点击
 */
- (void)titleClicked:(UIButton *)sender{
    HWDropdownMenu *menu = [HWDropdownMenu menu];
    menu.delegate = self;
    HWDropViewController *vc = [[HWDropViewController alloc] init];
    vc.view.height = 200;
    vc.view.width = 200;
    menu.dropVc = vc;
    [menu showFrom:sender];
}
#pragma mark - dropdownMenuDidshow
- (void)dropdownMenuDidShow:(HWDropdownMenu *)menu{
    UIButton *titleBtn =(UIButton *)self.navigationItem.titleView;
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
}
#pragma mark - dropdownMenuDidDismiss
- (void)dropdownMenuDidDismiss:(HWDropdownMenu *)menu{
    UIButton *titleBtn =(UIButton *)self.navigationItem.titleView;
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}
- (void)friendsearch
{
    HWLog(@"friendsearch");
}
- (void)pop
{
    HWLog(@"pop");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.statusFrames.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HWStatusCell *cell = [HWStatusCell cellWithTableView:tableView];
    cell.statusFrame = self.statusFrames[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HWStatusFrame *frame = self.statusFrames[indexPath.row];
    return frame.cellHeight;
}
@end
